import 'dart:async';

import 'package:fish_redux/fish_redux.dart';
import 'package:flutter/widgets.dart' hide Action;
import 'package:school_safe_teacher/constans/all_info.dart';
import 'package:school_safe_teacher/constans/constants.dart';
import 'package:school_safe_teacher/constans/route_constants.dart';
import 'package:school_safe_teacher/utils/sp_utils.dart';

import 'action.dart';
import 'state.dart';

Effect<SplashState> buildEffect() {
  return combineEffects(<Object, Effect<SplashState>>{
    SplashAction.action: _onAction,
    Lifecycle.initState: _init,
  });
}

void _onAction(Action action, Context<SplashState> ctx) {}

void _init(Action action, Context<SplashState> ctx) {
  print("===========================init==============================");
  ctx.state.countdownTimer =
      Timer.periodic(Duration(seconds: 1), (Timer timer) {
    if (ctx.state.countdownTime < 1) {
      ctx.state.countdownTimer.cancel();
      print(
          "===========================倒计时结束,进入下一页==============================");
      _onOpenIndexAction(action, ctx);
    } else {
      print("===========================倒计时=============================");
      ctx.state.countdownTime = ctx.state.countdownTime - 1;
      ctx.dispatch(SplashActionCreator.onCutDown());
    }
  });
}

Future<void> _onOpenIndexAction(Action action, Context<SplashState> ctx) async {
  // String userInfoStr = await SpUtil.getStringItem(Constants.SP_USER);
  String token = AllInfo.instance.token;

  String firstStart = await SpUtil.getStringItem(Constants.FIRST_START);
  if (firstStart != null && firstStart.isNotEmpty) {

      Navigator.of(ctx.context)
          .pushNamedAndRemoveUntil(RouteConstants.INDEX, (route) => false);

  } else {
    Navigator.of(ctx.context)
        .pushNamedAndRemoveUntil(RouteConstants.GUIDE, (route) => false);
  }
}
